package servlet;

import bean.User;
import com.alibaba.fastjson.JSON;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/addtoServlet")
public class AddtoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");// 设置请求参数的编码格式
        response.setContentType("text/json;charset=utf-8");// 设置网页界面相应的代码
        String line = request.getReader().readLine();
//        System.out.println(line);
        User user = JSON.parseObject(line, User.class);//拿到键值对
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("code");
        if (user.getCode().equalsIgnoreCase(code)) {//判断验证码
            UserService service = new UserService();
            //先查询数据库有没有，如果有，不让注册，如果没有继续注册
            String Msg="";
            boolean isNotEnroll = service.getByUsername(user.getUsername());
            if(isNotEnroll){
                int enroll = service.enroll(user);
                if (enroll>0){
                        Msg="true";
                    }else {
                        Msg="false";
                    }
                response.getWriter().write(Msg);
            }
        }else {
            response.getWriter().write("12");//验证码错误
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
